import logging
import time

import allure
from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from typing import List

"""
基类
"""


class BasePage:

    def __init__(self, driver_base: WebDriver = None):

        if not driver_base:
            logging.info("实例化ChromeDriver对象：debug模式")

            opt = webdriver.ChromeOptions()
            opt.debugger_address = "127.0.0.1:9222"
            self.driver = webdriver.Chrome(options=opt)
            self.driver.implicitly_wait(10)

            # 默认访问主页
            self.driver.get("https://work.weixin.qq.com/wework_admin/frame")
        else:
            self.driver = driver_base

    def find(self, by, locator) -> WebElement:
        """
        获取单个元素
        :param by:定位方式
        :param locator:表达式
        :return:
        """
        return self.driver.find_element(by, locator)

    def finds(self, by, locator) -> List[WebElement]:
        """
        获取一组元素
        :param by:定位方式
        :param locator:表达式
        :return:
        """
        return self.driver.find_elements(by, locator)

    def find_and_click(self, by, locator) -> WebElement:
        """
        获取并点击元素
        :param by:定位方式
        :param locator:表达式
        :return:
        """
        element = self.driver.find_element(by, locator)
        element.click()
        return element

    def wait_for_click(self, locator, timeout=10) -> WebElement:
        """
        显示等待并点击元素
        :param locator: 表达式
        :param timeout: 超时时间（单位:秒(s)）
        :return:WebElement
        """
        element: WebElement = WebDriverWait(self.driver, timeout).until(
            expected_conditions.element_to_be_clickable(locator))
        element.click()
        return element

    def do_screenshot(self, desc: str):
        timestamp = int(time.time())
        self.driver.save_screenshot(f"../pics/screenshot_{timestamp}.png")
        allure.attach.file(f"../pics/screenshot_{timestamp}.png", name=desc, attachment_type=allure.attachment_type.PNG)

    def close_driver(self):
        """关闭页面，保留进程"""
        self.driver.close()
